import Vue from 'vue'
import {
	login,
	logout
} from "@/api/login"
import {
	ACCESS_TOKEN,
	USER_NAME,
	USER_INFO,
	USER_AUTH,
	SYS_BUTTON_AUTH,
	UI_CACHE_DB_DICT_DATA,
	TENANT_ID,
	ORGLIST
} from "@/store/mutation-types"
import {
	welcome
} from "@/utils/util"
import {
	queryPermissionsByUser
} from '@/api/api'
import {
	getAction
} from '@/api/manage'

const user = {
	state: {
		token: '',
		username: '',
		realname: '',
		tenantid: '',
		welcome: '',
		avatar: '',
		orgList: [],
		permissionList: [],
		info: {},
		menuList: []
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, {
			username,
			realname,
			welcome
		}) => {
			state.username = username
			state.realname = realname
			state.welcome = welcome
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_PERMISSIONLIST: (state, permissionList) => {
			state.permissionList = permissionList
		},
		SET_MENULIST: (state, menuList) => {
			state.menuList = menuList
		},
		SET_INFO: (state, info) => {
			state.info = info
		},
		SET_TENANT: (state, id) => {
			state.tenantid = id
		},
		SET_ORGLIST: (state, orgList) => {
			state.orgList = orgList
		}
	},

	actions: {
		// CAS验证登录
		ValidateLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				getAction("/cas/client/validateLogin", userInfo).then(response => {
					console.log("----cas 登录--------", response);
					if (response.success) {
						const result = response.result
						const userInfo = result.userInfo
						Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						commit('SET_TOKEN', result.token)
						commit('SET_INFO', userInfo)
						commit('SET_NAME', {
							username: userInfo.username,
							realname: userInfo.realname,
							welcome: welcome()
						})
						commit('SET_AVATAR', userInfo.avatar)
						resolve(response)
					} else {
						resolve(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		Login({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				login(userInfo).then(response => {
					if (response.code == '00000') {
						const result = response.data
						const userInfo = result.userInfoVO
						Vue.ls.set(ACCESS_TOKEN, result.access_token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.loginName, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(ORGLIST, result.orgDTOList, 7 * 24 * 60 * 60 * 1000)
						// Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
						commit('SET_TOKEN', result.access_token)
						commit('SET_INFO', userInfo)
						commit('SET_ORGLIST', result.orgDTOList)
						commit('SET_NAME', {
							username: userInfo.loginName,
							realname: userInfo.realname,
							welcome: welcome()
						})
						commit('SET_AVATAR', userInfo.avatar)
						resolve(response)
					} else {
						reject(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetPermissionList({
			commit
		}) {
			return new Promise((resolve, reject) => {
				let v_token = Vue.ls.get(ACCESS_TOKEN);
				let params = {
					token: v_token
				};
				queryPermissionsByUser(params).then(response => {
					if (response.code == '00000') {
						const authData = response.data.auth;
						const allAuthData = response.data.allAuth;
						sessionStorage.setItem(USER_AUTH, JSON.stringify(authData));
						sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData));
						let menuData = response.data.menu;
						let permissionData = []
						for (let i = 0; i < menuData.length; i++) {
							permissionData.push.apply(permissionData, menuData[i].children)
						}
						if (permissionData && permissionData.length > 0) {
							//update--begin--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
							permissionData.forEach((item) => {
								if (item["children"]) {
									let hasChildrenMenu = item["children"].filter((i) => {
										return !i.hidden || i.hidden == false
									})
									if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
										item["hidden"] = true
									}
								}
							})
							//console.log(" menu show json ", menuData)
							//update--end--autor:qinfeng-----date:20200109------for：JEECG-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
							//将页面设置到本地存储，当页面跳转时,路由守卫判断是否为空
							// menuData.splice(1,1)
							// console.log(JSON.stringify(menuData))
							commit('SET_PERMISSIONLIST', permissionData)
							commit('SET_MENULIST', menuData)
						} else {
							reject('请为该登录用户授权后，在进行登录')
						}
						resolve(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 登出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				let logoutToken = state.token;
				commit('SET_TOKEN', '')
				commit('SET_PERMISSIONLIST', [])
				commit('SET_ORGLIST', [])
				Vue.ls.remove(ACCESS_TOKEN)
				Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
				Vue.ls.remove(ORGLIST)
				Vue.ls.set(ORGLIST, [], 7 * 24 * 60 * 60 * 1000)
				//console.log('logoutToken: '+ logoutToken)
				logout(logoutToken).then(() => {
					//let sevice = "http://"+window.location.host+"/";
					//let serviceUrl = encodeURIComponent(sevice);
					//window.location.href = window._CONFIG['casPrefixUrl']+"/logout?service="+serviceUrl;
					resolve()
				}).catch(() => {
					resolve()
				})
			})
		},
		saveTenant({
			commit
		}, id) {
			Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
			commit('SET_TENANT', id)
		}
	}
}

export default user
